/* MethodResponse.cs -- 
   Copyright (C) 2008  Casey Marshall.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.  */


using System;
using SexpSharp;

namespace SexpSharp.RPC
{
	public sealed class MethodResponse
	{
		private string name;
		private IValue retval;

		public MethodResponse(string name, IValue retval)
		{
			if (name.Length == 0)
				throw new ArgumentException("must be a nonempty string", "name");
			this.name = name;
			this.retval = retval;
		}

		public MethodResponse(Expression expr)
		{
			List list = expr as List;
			if (list == null)
				throw new ArgumentException("must be a list", "expr");
			if (list.Count < 2 || !(list.First is Atom) || !(list.Second is Atom)
				|| list.Count > 3)
				throw new ArgumentException("list must begin with two atoms, and can't exceed three elements");
			if (list.First.ToString() != "method-response")
				throw new ArgumentException("first atom must be 'method-response'");
			name = list.Second.ToString();
			if (list.Count == 3)
				retval = Values.ExpressionToValue(list.Rest.Second);
			else
				retval = null;
		}

		public string Name
		{
			get { return name; } 
		}

		public IValue ReturnValue
		{
			get { return retval; }
		}

		public Expression ToExpression()
		{
			List list = new List();
			list.Add(new Atom("method-response"));
			list.Add(new Atom(name));
			if (retval != null)
				list.Add(retval.ToExpression());
			return list;
		}
	}
}